import instance from "./axiosInstance";
import { saveTokenInfo } from "@/utils/auth";

// 生成二维码
export const requestGenerateQR = async () => {
  try {
    const response = await instance({
      method: "GET",
      url: "/user/qr",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    });
    return response.data;
  } catch (error) {
    console.error("生成二维码请求异常:", error);
    throw error;
  }
};

// 刷新二维码
export const requestRefreshQR = async (qrString) => {
  try {
    const response = await instance({
      method: "GET",
      url: "/user/qr/refresh",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params: { qrString },
    });
    return response.data;
  } catch (error) {
    console.error("刷新二维码请求异常:", error);
    throw error;
  }
};

// web端收到websocket信息后发送该请求确认登录
export const confirmLogin = async (qrString) => {
  try {
    const response = await instance({
      method: "GET",
      url: "/user/qr/login",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params: { qrString },
    });
    console.log(response.data);
    return response.data;
  } catch (error) {
    console.error("确认登录请求异常:", error);
    throw error;
  }
};

// 手机号登录
export const phoneLogin = async (phone) => {
  try {
    const response = await instance({
      method: "POST",
      url: `/user/web/login/${phone}`,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    });
    return response.data;
  } catch (error) {
    console.error("手机号登录请求异常:", error);
    throw error;
  }
};

// 刷新AccessToken
export const fetchNewTokenByRefreshToken = async () => {
  try {
    const refreshToken = localStorage.getItem("refreshToken");
    const response = await instance({
      method: "POST",
      url: "/user/refresh",
      headers: { "Content-Type": "application/json" },
      data: { refreshToken },
    });

    if (response.data.code !== 0) {
      throw new Error(response.data.message || "刷新Token失败");
    }

    // 检查返回数据的完整性
    if (
      !response.data.data ||
      !response.data.data.accessToken ||
      !response.data.data.refreshToken ||
      !response.data.data.accessExpiresIn
    ) {
      throw new Error("刷新Token失败：返回数据不完整");
    }

    saveTokenInfo(response.data.data);

    return response.data;
  } catch (error) {
    console.error("Token刷新失败:", error);
    throw error;
  }
};

// 退出登录接口
export const logout = async () => {
  try {
    const response = await instance({
      method: "POST",
      url: "/user/logout",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      data: {},
    });
    return response.data;
  } catch (error) {
    console.error("退出登录请求异常:", error);
    throw error;
  }
};
